#include "SHT21.h"
#include<rtthread.h>

#define SHT21_ADDRESS	0x80	//温湿度从机地址

double T = 0;	//温度
double RH = 0;	//湿度

uint8_t Data[2] = {0};	//临时数据变量

/*外设初始化*/
void SHT21_Init(void)
{
	MyI2C_Init();
}

/*发送测量温度命令*/
void SHT21_T_measurement(void)
{
	MyI2C_Start();
	MyI2C_SendByte(SHT21_ADDRESS);
	MyI2C_ReceiveAck();
	MyI2C_SendByte(0xF3);
	MyI2C_ReceiveAck();
//	rt_thread_mdelay(1);
//	Delay_us(30);
	MyI2C_Stop();
}

/*发送测量湿度命令*/
void SHT21_RH_measurement(void)
{
	MyI2C_Start();
	MyI2C_SendByte(SHT21_ADDRESS);
	MyI2C_ReceiveAck();
	MyI2C_SendByte(0xF5);
	MyI2C_ReceiveAck();
//	rt_thread_mdelay(1);
//	Delay_us(30);
	MyI2C_Stop();
}

/*读取数据*/
uint8_t SHT21_Read_Data(void)
{
	uint8_t Ack = 1;	//检测是否测量完成标志位
	
	MyI2C_Start();
	MyI2C_SendByte(SHT21_ADDRESS | 0x01);
	Ack = MyI2C_ReceiveAck();
	/*若接收到非应答信号，则说明测量未完成*/
	if(Ack)
	{
		MyI2C_Stop();
		return 1;
	}
	Data[0] = MyI2C_ReceiveByte();
	MyI2C_SendAck(0);
	Data[1] = MyI2C_ReceiveByte();
	/*不需要校验，直接停止*/
	MyI2C_SendAck(1);
	MyI2C_Stop();
	return 0;
}

/*处理测量温度值*/
void SHT21_T_Data(void)
{
	uint16_t T_Data = 0;
	
	SHT21_T_measurement();
	if(SHT21_Read_Data())
	{
		OLED_Printf(0,32,OLED_8X16,"T Data err");
		OLED_UpdateArea(0,32,128,16);
	}
	/*将Data[1]的低两位清零，然后将Data[0]Data[1]合并成16位数据*/
	Data[1] &= 0xFC;
	T_Data = (uint16_t)Data[0] << 8; 
	T_Data |= Data[1];
	
	T = -46.85f + 175.72 * (double)(T_Data / 65535.0);
}

/*处理测量湿度值*/
void SHT21_RH_Data(void)
{
	uint16_t RH_Data = 0;
	
	SHT21_RH_measurement();
	if(SHT21_Read_Data())
	{
		OLED_Printf(0,32,OLED_8X16,"RH Data err");
		OLED_UpdateArea(0,32,128,16);
	}
	/*将Data[1]的低两位清零，然后将Data[0]Data[1]合并成16位数据*/
	Data[1] &= 0xFC;
	RH_Data = (uint16_t)Data[0] << 8; 
	RH_Data |= Data[1];
	
	RH = -6 + 125 * (double)(RH_Data / 65535.0);
}

void SHT21_Show_Data(void)
{
	/*获取温度*/
	SHT21_T_measurement();
	if(SHT21_Read_Data())
	{
		OLED_Printf(0,48,OLED_8X16,"T time err");
		OLED_UpdateArea(0,48,128,16);
	}
	SHT21_T_Data();
	/*获取湿度*/
	SHT21_RH_measurement();
	if(SHT21_Read_Data())
	{
		OLED_Printf(0,48,OLED_8X16,"RH time err");
		OLED_UpdateArea(0,48,128,16);
	}
	SHT21_RH_Data();
	
	/*温控*/
	if(T >= 20)
	{
		Motor_start();
		Motor_A_Z();
	}
	else
	{
		Motor_stop('A');
	}
	
	/*湿控*/
	if(RH <= 70)
	{
		Motor_start();
		Motor_B_F();
	}
	else
	{
		Motor_stop('B');
	}
	
	/*打印*/
	OLED_Printf(0,32,OLED_8X16,"T:%.1f RH:%.1f",T,RH);
	OLED_UpdateArea(0,32,128,16);
}

